const path = require("path");
const {toUrl} = require('./path-extend')
//根据路劲获取目标对象

function getTargetByPath(pathStr, resource) {
  let target = resource;
  pathStr = pathStr.split('/').slice(1);
	for(let pro of pathStr) {
    target = target[pro];
  }
	return target;
}

//controller mountModule 挂载模块 routerModulePath 路由路径  mountWay 挂载方式 mountPath 挂载路径 
function mountRouter({router, controller, controllerMethodPath, mountPath, mountWay, mountModule}){
  for(let methodName of mountModule) {
    let controllerMethodName , mountedName ;
    if(methodName instanceof Array) {					//如果是数组
      controllerMethodName = methodName[0];
      mountedName =  methodName[1];
    }else if(typeof methodName === "string"){		//如果是字符串
      controllerMethodName = mountedName = methodName;
    }else {
      throw new Error(methodName + "'s type is error!");
    }
    const mountMethod = getTargetByPath(toUrl(path.join(controllerMethodPath, controllerMethodName)), controller); //获取方法
    router[mountWay](toUrl(path.join(mountPath, mountedName)) , mountMethod);	//挂载监听
  }
}

function mountRouterMap(router, controller, routerMap) {
  //遍历路由模块
	for(let routerModuleName in routerMap) {
		const routerModule = routerMap[routerModuleName];	//获得模块
    //对应controller路径
		const controllerMethodPath = routerModule.controllerMethodPath;	//访问方法path
    //挂载路径   web访问路径 如果无则,和访问方法path相同
		const mountPath =  routerModule.mountPath || controllerMethodPath;	
    //遍历挂载路由
		for(let mountWay in routerModule.mount) {		//遍历路由映射
			//挂载模块
			const mountModule = routerModule.mount[mountWay];	//方式模块
      //判别挂载方法
      const mountRouterConfig = {
        //路由调用
        router,
        //controller方法源
        controller,
        //控制器路径
        controllerMethodPath,
        //要挂载的路径
        mountPath,
        //挂载方式
        mountWay,
        //要挂载模块
        mountModule,
      }
      mountRouter(mountRouterConfig);
		}
	}
}

module.exports = mountRouterMap;